<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/24
 * Time: 14:41
 * 分享统计
 */

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\FundsRecord;
use app\common\model\ShareRecord;
use think\Db;
use think\Exception;

class Share extends Api {
	protected $noNeedRight = '*';
	
	public function addRecord() {
		$model = new ShareRecord();
		$userId = $this->auth->id;
		$config = Db::name('settingShare')
			->find();
		
		Db::startTrans();
		try {
			//分享类型
			$type = input('post.type');
			$logData = [
				'user_id' => $userId,
				'type' => $type,
				'gift_type' => '',
				'gift_amount' => 0
			];
			
			//查找分享配置
			if($config && $config['gift_amount'] > 0 && $config['day_number'] > 0) {
				//查找分享次数
				$count = Db::name('shareRecord')
					->where(['user_id' => $userId, 'create_time' => ['egt', strtotime(date('Y-m-d'))]])
					->count();
			
				if($count < $config['day_number']) {
					$logData['gift_type'] = $config['gift_type'];
					$logData['gift_amount'] = $config['gift_amount'];
					
					
					$user = Db::name('user')->find($userId);
					//给用户加钱
					switch ($config['gift_type']) {
						case FundsRecord::ACCOUNT_TYPE_BALANCE:
							$userData['balance'] = $user['balance'] + $config['gift_amount'];
							$beforeAmount = $user['balance'];
							break;
						case FundsRecord::ACCOUNT_TYPE_INTEGRAL:
							$userData['integral'] = $user['integral'] + $config['gift_amount'];
							$beforeAmount = $user['integral'];
							break;
						case FundsRecord::ACCOUNT_TYPE_PHONE:
							$userData['phone_balance'] = $user['phone_balance'] + $config['gift_amount'];
							$beforeAmount = $user['phone_balance'];
							break;
						case FundsRecord::ACCOUNT_TYPE_VOUCHER:
							$userData['voucher_balance'] = $user['voucher_balance'] + $config['gift_amount'];
							$beforeAmount = $user['voucher_balance'];
							break;
						case FundsRecord::ACCOUNT_TYPE_DEPOSIT:
							$userData['deposit_balance'] = $user['deposit_balance'] + $config['gift_amount'];
							$beforeAmount = $user['deposit_balance'];
							break;
						default:
							throw new Exception('未知赠送类型');
					}
					
					$userRes = Db::name('user')
						->where(['id' => $userId])
						->update($userData);
					if(!$userRes) {
						throw new Exception('添加赠送金额出错');
					}
					
					//添加流水记录
					$logModel = new FundsRecord();
					$logRes = $logModel->addRecord($userId, $config['gift_amount'], $beforeAmount, $config['gift_type'], $logModel::OPE_TYPE_PLUS, $logModel::TYPE_SHARE_GIFT,'', '分享赠送');
					if(!$logRes) {
						throw new Exception('添加资金记录出错');
					}
				}
			}
			
			//添加记录
			$res = $model->allowField(true)
				->isUpdate(false)
				->save($logData);
			
			if(!$res) {
				throw new Exception('添加分享记录出错');
			}
			
			Db::commit();
			$this->success('添加成功');
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
	}
}